package com.yuandian.ops.workbench.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.ops.workbench.mapper.BusiStatusAlarmStatMapper;
import com.yuandian.ops.workbench.po.AlarmListParams;
import com.yuandian.ops.workbench.po.StatusAlarmStatParams;
import com.yuandian.ops.workbench.service.IAreaAlarmAnalysisService;
import com.yuandian.ops.workbench.vo.*;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 运维工作台 - 区域告警分析
 *
 * @Author pmx
 * @Date 2021/07/08
 */
@Service("areaAlarmAnalysisService")
public class AreaAlarmAnalysisServiceImpl implements IAreaAlarmAnalysisService {

	@Autowired
	private BusiStatusAlarmStatMapper busiStatusAlarmStatMapper;

	private final String[] completionState = new String[]{"不完整", "完整"};

	private final String[] dealState = new String[]{"失败", "成功"};


	/**
	 * 查询趋势图数据
	 * @param params 请求对象
	 * @return 返回对象
	 */
	@Override
	public List<BusiStatusAlarmStatVo> queryAreaTrend(StatusAlarmStatParams params) {
		List<BusiStatusAlarmStatVo> resultList = new ArrayList<>();
		String tableName = "dws_business_status_alarm_stat";
		List<BusiStatusAlarmStatVo> list = busiStatusAlarmStatMapper.queryStatusAlarmStatByArea(null, params);
		if(list != null && list.size() > 0) {
			Map<String, BusiStatusAlarmStatVo> map = new HashMap<>();
			for(BusiStatusAlarmStatVo vo : list) {
				map.put(vo.getCycleTime(), vo);
			}
			long start = DateUtil.parse(params.getStartTime()).getTime();
			long end = DateUtil.parse(params.getEndTime()).getTime();
			while (start < end) {
				String cycleTime = DateUtil.formatDateTime(new Date(start));
				if(map.get(cycleTime) != null) {
					resultList.add(map.get(cycleTime));
				} else {
					BusiStatusAlarmStatVo vo = new BusiStatusAlarmStatVo();
					vo.setAreaCode(params.getAreaCode());
					vo.setCount(0);
					vo.setCompleteCount(0);
					vo.setAlarmCount(0);
					vo.setFailCount(0);
					vo.setAvgServerResponseTime(0);
					vo.setHealthRate(0);
					vo.setCycleTime(cycleTime);
					resultList.add(vo);
				}
				start = start + 300L * 1000;
			}
		}
		return resultList;
	}

	/**
	 * 查询健康度告警趋势图
	 * @param alarmListParams 请求对象
	 * @return 返回对象
	 */
	@Override
	public List<AlarmTrendVo> queryAlarmTrend(AlarmListParams alarmListParams) {
		List<AlarmTrendVo> resultList = new ArrayList<>();
		alarmListParams.setStartTime(alarmListParams.getStartTime().substring(0, alarmListParams.getStartTime().indexOf(" ")) + " 00:00:00");
		alarmListParams.setDataType(2);
		List<AlarmDetailListVo> list = busiStatusAlarmStatMapper.alarmDetailList(null, alarmListParams);
		Map<String, AlarmDetailListVo> map = new HashMap<>();
		if(!CollectionUtils.isEmpty(list)) {
			map = list.stream().collect(Collectors.toMap(AlarmDetailListVo::getCycleTime, v -> v, (k1, k2) -> k1));
			long start = Objects.requireNonNull(DateUtil.parse(alarmListParams.getStartTime())).getTime();
			long end = Objects.requireNonNull(DateUtil.parse(alarmListParams.getEndTime())).getTime();
			while (start < end) {
				AlarmTrendVo vo = new AlarmTrendVo();
				String cycleTime = DateUtil.formatDateTime(new Date(start));
				vo.setCycleTime(cycleTime);
				if(map.get(cycleTime) != null) {
					vo.setHealthRate(Float.parseFloat(map.get(cycleTime).getHealthRate()));
				} else {
					vo.setHealthRate(0F);
				}
				resultList.add(vo);
				start = start + 60L * 1000;
			}
		}
		return resultList;
	}


	/**
	 * 查询当天历史列表
	 * @param alarmListParams 请求对象
	 * @return 返回对象
	 */
	@Override
	public PageDataInfo queryHistoryData(AlarmListParams alarmListParams) {
		Page<AlarmHistDetailListVo> page = null;
		if(alarmListParams.getPageNum()>0 && alarmListParams.getPageSize()>0) {
			page = new Page<>(alarmListParams.getPageNum(), alarmListParams.getPageSize());
			//mybatis-plus pageSize为-1 时,代表查询全部
		}else if(alarmListParams.getPageSize() == -1) {
			page = new Page<>(alarmListParams.getPageNum(), alarmListParams.getPageSize());
		}else {
			page = new Page<>();
		}

		alarmListParams.setDataType(2);
		List<AlarmHistDetailListVo> list = new ArrayList<>();

		list = busiStatusAlarmStatMapper.alarmHistDetailList(page, alarmListParams);
		list.forEach(alarmHistDetailListVo -> {
			// 4.0版本已去掉低密度告警统计
//            if (alarmHistDetailListVo.getAlarmType()==2){
//                alarmHistDetailListVo.setAlarmTypeStr("低密度归并告警");
//            }else{
			alarmHistDetailListVo.setAlarmTypeStr("正常告警");
//            }
		});
		return new PageDataInfo(page, list);
	}

	/**
	 * 查询区域告警详情
	 *
	 * @param alarmListParams 请求对象
	 * @return 返回对象
	 */
	@Override
	public AlarmAnalysisVo queryAlarmByArea(AlarmListParams alarmListParams) {
		Date cycleTime = DateUtil.parse(alarmListParams.getCycleTime());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(cycleTime);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		String startTime = YDateUtil.formatDateTime(calendar.getTime());
		calendar.add(Calendar.DAY_OF_YEAR, 1);
		String endTime = YDateUtil.formatDateTime(calendar.getTime());
		alarmListParams.setStartTime(startTime);
		alarmListParams.setEndTime(endTime);
		alarmListParams.setDataType(2);

		// 查询基本信息
		AlarmAnalysisVo vo = busiStatusAlarmStatMapper.alarmAreaAnalysis(alarmListParams);

		// 查询告警数、最早告警时间、最新告警时间
		if (vo != null) {
			alarmListParams.setAreaCode(vo.getAreaCode());
			alarmListParams.setAlarmIndicatorCode(vo.getAlarmIndicatorCode());
			AlarmAnalysisVo alarmBoundaryVo = busiStatusAlarmStatMapper.getAlarmBoundaryValueInfo(alarmListParams);
			if (alarmBoundaryVo != null) {
				vo.setAlarmNum(alarmBoundaryVo.getAlarmNum());
				vo.setMinAlarmTime(alarmBoundaryVo.getMinAlarmTime());
				vo.setMaxAlarmTime(alarmBoundaryVo.getMaxAlarmTime());
			}
		}

		return vo;
	}


	/**
	 * 区域-全系统详情
	 * @param params 请求对象
	 * @return 返回对象
	 */
	@Override
	public PageDataInfo querySystemStatByArea(StatusAlarmStatParams params) {
		Page<BusiStatusAlarmStatVo> page = (params.getPageNum() > 0 && params.getPageSize() > 0) ?
				new Page<>(params.getPageNum(), params.getPageSize()) : new Page<>();

		List<BusiStatusAlarmStatVo> list = busiStatusAlarmStatMapper.statData(page, params);
		return new PageDataInfo(page, list);
	}

	/**
	 * 查询区域-系统-全业务详情
	 * @param params 请求对象
	 * @return 返回对象
	 */
	@Override
	public PageDataInfo queryDataBySystem(StatusAlarmStatParams params) {
		Page<BusiStatusAlarmStatVo> page = (params.getPageNum() > 0 && params.getPageSize() > 0) ?
				new Page<>(params.getPageNum(), params.getPageSize()) : new Page<>();

		List<BusiStatusAlarmStatVo> list = busiStatusAlarmStatMapper.queryStatusAlarmStat(page, params);
		return new PageDataInfo(page, list);
	}

	/**
	 * 运维工作台 -> 首页地图下钻 -> 历史告警列表 -> 告警分析 -> 失败数、告警数下钻详单列表
	 *
	 * @param params 请求对象
	 * @return 返回对象
	 */
	@Override
	public PageDataInfo alarmTypeToBusinessList(StatusAlarmStatParams params) {
		Page<BusinessDetailedListVo> page = new Page<>(params.getPageNum(), params.getPageSize());
		List<BusinessDetailedListVo> result = new ArrayList<>();
		// 查询步骤表获取详单ID列表
		params.setIsAlarm(1);
		List<String> detailIdList = busiStatusAlarmStatMapper.getDetailIdFromStepTable(params);

		// 查询详单表获取相关数据
		if (detailIdList != null && detailIdList.size() > 0) {
			params.setDetailIdList(detailIdList);
			result = busiStatusAlarmStatMapper.getDetailDataList(page, params);
		}

		for (BusinessDetailedListVo vo : result) {
			vo.setCompletionState(completionState[Convert.toInt(vo.getCompletionState())]);
			vo.setDealState(dealState[Convert.toInt(vo.getDealState())]);
		}

		// 返回结果集
		return new PageDataInfo(page, result);
	}


	/**
	 * 三级-地图下钻-历史告警列表下钻-关联告警列表
	 * @param params 请求对象
	 * @return 返回对象
	 */
	@Override
	public PageDataInfo alarmDetailListQuery(AlarmListParams params) {
		// 5-高频业务，6-經常业务，7-低频业务，8-零散业务
		params.setDataTypeList(Arrays.asList(5, 6, 7, 8));

		Page<AlarmDetailListVo> page = new Page<>(params.getPageNum(), params.getPageSize());
		List<AlarmDetailListQueryVo> list = busiStatusAlarmStatMapper.alarmDetailListQuery(page, params);
		// 初始化用于下载的'序号'
		int index = 1;
		if (params.getPageSize() == -1 && !CollectionUtils.isEmpty(list)) {
			for (AlarmDetailListQueryVo vo : list) {
				vo.setNum(index++);

				if (Objects.equals(vo.getAlarmIndicatorCode(), "BS_FAIL_RATE_10")) {
					vo.setAlarmIndicatorName("业务失败率");
				} else if (Objects.equals(vo.getAlarmIndicatorCode(), "BS_FAIL_RATE_20")) {
					vo.setAlarmIndicatorName("响应慢");
				} else if (Objects.equals(vo.getAlarmIndicatorCode(), "BS_FAIL_RATE_30")) {
					vo.setAlarmIndicatorName("健康度低");
				}
			}
		}
		return new PageDataInfo(page, list);
	}

}
